﻿///***************************************************************
/// 시  스  템 : Updms.Cfg
/// 단위시스템 : CFG
/// 계      층 : Presentation Layer
/// 프로그램명 : Cfg1012m
/// 파  일  명 : Cfg1012m.aspx.cs
/// 설      명 : SQL실행기
///***************************************************************
/// 수정ID 일자       이름     내용
///---------------------------------------------------------------
/// CH001  2008-08-11 송시명   최초 작성
///***************************************************************
using System;
using System.Data;
using System.Collections;
using System.Web.UI;
using System.Web.UI.WebControls;

using SMFramework.Data;
using SMFramework.Utility;

using Base.AppFramework.Web.UI.CommandBar;
using Base.Dac;

using Updms.Cfg.Exe;


namespace Updms.Cfg
{
	public partial class Cfg1012m : Updms.Common.BaseClass.PageBase
	{
		#region 전역영역

		//프로그램상수
		public static readonly string PID = "Cfg1012m";
		public static readonly string gs_path_info = "/updms/Cfg/" + PID + ".aspx";

		Global global = new Global();		

		//검색
		protected string kw1 = "";	// ls_database
		protected string kw2 = "";	// ls_table

		//메뉴 선택값
		protected string gs_sm = "";

		#endregion

		#region Page_Load, OnPageLoad

		protected void Page_Load(object sender, EventArgs e)
		{
			SetInit();
			if (!Page.IsPostBack)
			{
				// 최초 화면 로딩시 처리해야 할 부분
				OnPageLoad();
				SetTableInfo();
			}
		}

		// OnPageLoad
		private void OnPageLoad()
		{
			SetLiterals(global.GetLabelInfoByPgmId(PID, LANG_SET));
			SetSearchParameter();
		}

		#endregion

		#region InitializeComponent

		private void InitializeComponent()
		{
			this.Load += new System.EventHandler(this.Page_Load);
			this.PreRender += new System.EventHandler(this.Page_PreRender);
		}

		#endregion		

		#region SetInit, SetSearchParameter

		//초기값설정
		private void SetInit()
		{
			lbl_search_flag.Text = "INIT";			

			gs_sm = (Request.QueryString["sm"] == null || Request.QueryString["sm"].Trim().Length != 7)
					? global.GetDirDepth(PID) : Request.QueryString["sm"].ToString();
		}

		//검색파라미터
		private void SetSearchParameter()
		{
			switch (lbl_search_flag.Text.Trim().ToUpper())
			{
				case "INIT":
					if (String.IsNullOrEmpty(Request.QueryString["kw1"]))	// url에 값이 없으면
					{
						kw1 = "UPDMS";
					}
					else
					{
						kw1 = Server.UrlDecode(Request.QueryString["kw1"]);
					}
					if (String.IsNullOrEmpty(Request.QueryString["kw2"]))	// url에 값이 없으면
					{
						kw2 = "UPDMS";
					}
					else
					{
						kw2 = Server.UrlDecode(Request.QueryString["kw2"]);
					}
					
					break;
				case "SEARCH":
					kw1 = "UPDMS";
					kw2 = "UPDMS";
					break;
			}
		}		

		#endregion

		#region 마스터 Method (SetTableInfo, SetFieldInfo)

		//테이블 바인딩
		private void SetTableInfo()
		{
			DataSet lo_ds = new DataSet();

			using (Cfg1012m_NT _Cfg1012m_NT = new Cfg1012m_NT())
			{
				lo_ds.Merge(_Cfg1012m_NT.GetUpdmsTableInfo(kw1));	//UPDMS_COM
			}

			ddl_table.Items.Clear();
			ddl_table.DataSource = lo_ds;
			ddl_table.DataMember = "UPDMS_CFG_SQL_EXECUTE";
			ddl_table.DataTextField = "TABLE_NAME";
			ddl_table.DataValueField = "TABLE_NAME";
			ddl_table.DataBind();
			ddl_table.Items.Insert(0, new ListItem(DDL_SELECT, ""));
		}

		//필드 바인딩
		private void SetFieldInfo(string ls_table)
		{
			DataSet lo_ds = new DataSet();
			DataPack lo_dp = new DataPack();

			lo_dp.AddProperty("ls_table", typeof(string), ls_table);

			using (Cfg1013m_NT _Cfg1013m_NT = new Cfg1013m_NT())
			{
				lo_ds.Merge(_Cfg1013m_NT.GetSpColumnsEx(lo_dp));
			}

			GridView2.DataSource = lo_ds;
			GridView2.DataBind();
		}
		
		#endregion

		#region 디테일 Method (CopyAsClipboard)
		
		private void CopyAsClipboard()
		{
			string ls_column_name = "";
			for (int i = 0; i < GridView2.Rows.Count; i++)
			{
				Label lbl_column_name = (Label)GridView2.Rows[i].FindControl("lbl_column_name");				
				ls_column_name += lbl_column_name.Text +",\\n";
			}
			
			//마지막 쉼표(,)제거
			string ls_column_names = ls_column_name.Substring(0, ls_column_name.LastIndexOf(","));
			ScriptManager.RegisterClientScriptBlock(this.Page, this.GetType(), null, "copyAsClipboard('" + ls_column_names + "', true);", true);
		}

		#endregion

		#region CRUD (SelectProcess, SearchProcess)

		//조회
		private void SelectProcess()
		{
			DataSet lo_ds = new DataSet();

			try
			{
				using (Cfg1012m_NT _Cfg1012m_NT = new Cfg1012m_NT())
				{
					lo_ds.Merge(_Cfg1012m_NT.SelectProcess(txt_query.Text));
				}

				GridView1.DataSource = lo_ds;
				GridView1.DataBind();
			}
			catch(Exception ex)
			{
				CallExceptionMsgBoxInAjax(ex);
			}

			//결과출력(키워드, 검색행수)
			lbl_result_count.Text = DataSetUtil.GetRowCount(lo_ds, "UPDMS_CFG_SQL_EXECUTE").ToString();
		}		

		//검색
		private void SearchProcess()
		{
			lbl_search_flag.Text = "SEARCH";
			SetSearchParameter();
			SelectProcess();
			SetTableInfo();
		}

		#endregion		

		#region Page_PreRender, ChangePageMode

		// Page_PreRender
		private void Page_PreRender(object sender, System.EventArgs e)
		{
			if (!Page.IsPostBack)
			{
				using (AccessCheck access = new AccessCheck())
				{
					//접근권한 체크
					if (!access.CheckPgmAccessGrant(PID, USER_ID, ACCESS_LOG_INFO))
					{
						Response.Redirect(URL_NO_AUTHORITY_REDIRECT_BASE);	//사용자의 권한은 요청하신 페이지를 볼 수 없습니다
					}
					//사용권한별 버튼처리
					PagePreRender.SetVisibleCtrl(this, access.CheckPgmUsingGrant(USER_DIV, PID), access.GetVisibleCtrl(PID));
				}
			}
			ChangePageMode();
		}

		//ChangePageMode
		private void ChangePageMode()
		{
			SetGridViewHeader(global.GetColumnListByPgmId(PID, LANG_SET));
		}

		#endregion

		#region GridView이벤트

		//RowDataBound
		protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//번호
				e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();

				for (int i = 1; i < e.Row.Cells.Count; i++)
				{
					e.Row.Cells[i].HorizontalAlign = HorizontalAlign.Left;
				}
			}
		}
		
		//RowDataBound
		protected void GridView2_RowDataBound(object sender, GridViewRowEventArgs e)
		{
			if (e.Row.RowType == DataControlRowType.DataRow)
			{
				//마우스올렸을 때
				e.Row.Attributes.Add("onMouseOver", GRID_ONMOUSEOVER_COLOR);
				e.Row.Attributes.Add("onMouseOut", GRID_ONMOUSEOUT_COLOR);

				//번호
				e.Row.Cells[0].Text = (e.Row.RowIndex + 1).ToString();

				//길이
				string type_name = e.Row.Cells[3].Text;
				string precision = e.Row.Cells[4].Text;
				string scale = GridView2.DataKeys[e.Row.RowIndex].Values["SCALE"].ToString();

				switch (type_name)
				{
					case "int":
					case "int identity":
					case "decimal":
					case "float":
					case "double":
						if (ConversionUtil.ExtractNumberInt(scale) > 0)
						{
							precision = precision + ", " + scale;
						}
						break;
					case "char":
					case "nchar":
					case "varchar":
					case "nvarchar":
					case "text":
					case "ntext":
						if (ConversionUtil.ExtractNumberInt(precision) > 8000)
						{
							precision = "-1";
						}
						break;
					case "datetime":
						precision = "";
						break;
				}
				e.Row.Cells[4].Text = precision;
			}
			
			//Footer에 테이블명 바인딩
			if (e.Row.RowType == DataControlRowType.Footer)
			{
				e.Row.Cells[0].Text = "Table Name";
				e.Row.Cells[0].Attributes.Add("class", "total");
				e.Row.Cells[0].ColumnSpan = 2;
				e.Row.Cells[1].Visible = false;
				e.Row.Cells[2].Text = ddl_table.SelectedItem.Text;
				e.Row.Cells[2].Attributes.Add("class", "total");
				e.Row.Cells[2].ColumnSpan = 4;
				e.Row.Cells[3].Visible = false;
				e.Row.Cells[4].Visible = false;
				e.Row.Cells[5].Visible = false;
				e.Row.Cells[6].Visible = false;
			}
		}

		#endregion

		#region 버튼이벤트

		//검색
		protected void ibtn_exec_Click(object sender, EventArgs e)
		{
			SearchProcess();
		}
		
		//엑셀
		protected void ibtn_excel_Click(object sender, EventArgs e)
		{
			DataSet lo_ds = new DataSet();
			
			using (Cfg1012m_NT _Cfg1012m_NT = new Cfg1012m_NT())
			{
				lo_ds.Merge(_Cfg1012m_NT.SelectProcess(txt_query.Text));
			}
			string fileName = PID + "(" + global.GetMenuTitle(PID, LANG_SET) + ")";
			ExcelUtil.CreateExcelFileX(this.Page, fileName, lo_ds);
		}

		//테이블 선택시
		protected void ddl_table_SelectedIndexChanged(object sender, EventArgs e)
		{
			SetFieldInfo(ddl_table.SelectedItem.Value);
		}

		//복사
		protected void lbtn_column_name_Click(object sender, EventArgs e)
		{
			CopyAsClipboard();
		}

		#endregion
		
	}
}
